import api from '../../config/api'
import request from '../../utils/request'
import { shareOptions } from '../../utils/access'
import { jump, parse } from '../../utils/utils'

// pages/recycleOrderConfirm/recycleOrderConfirm.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 物品列表
    categoryList: [],
    // 选中物品源列表
    selectedOriginList: [],
    // 选中物品列表
    selectedList: [],
    // 回收金额
    amount: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const params = parse(options?.obj)
    console.log('确认订单页面参数：', params)
    const list = params?.selectedList || []
    this.setData({
      id: params.id,
      selectedList: list,
      selectedOriginList: list
    })
    this.getThing()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 获取所有物品
   */
  async getThing() {
    let res = await request.get(api.getRecycleGoodsList,{},{ loading: false })
    console.log('物品：', res)

    if (res.httpStatus == 200) {
      res.data.map((item) => {
        item.value = 1
        item.selected = false
      })
      this.setData({
        categoryList: res.data.map(item => ({
          ...item,
          focus: false,
          selected: this.data.selectedList.some((f) => f.id === item.id)
        }))
      })
    }
  },
  /**
   * 选择种类
   */
  handleSelected(e) {
    const { categoryList, selectedList } = this.data
    const { dataset = {} } = e.currentTarget

    const list = categoryList.map(item => (
      {
        ...item,
        selected: item.id === dataset.id ? !item.selected : item.selected,
        value: item.id === dataset.id ? 1 : item.value,
      }
    ))
    const newSelectedList = list.filter(item => item.selected).map(item => {
      const findItem = selectedList.find((f) => f.id === item.id)
      return {
        ...item,
        value: findItem ? findItem.value : 1
      }
    })

    this.setData({
      categoryList: list,
      selectedList: newSelectedList,
    })
  },
  /**
   * 清空已选择的物品
   */
  handleEmpty() {
    const { categoryList } = this.data

    const list = categoryList.map(item => (
      {
        ...item,
        selected: false,
        value: 1,
      }
    ))

    this.setData({
      categoryList: list,
      selectedList: [],
    })
  },
  // 表单聚焦
  listFocus(event) {
    const { selectedList } = this.data
    const index = event.currentTarget.dataset.index
    this.setData({
      selectedList: selectedList.map((item, i) => ({
        ...item,
        focus: i === index
      }))
    })
  },
  // 物品重量&回收金额输入
  fieldInput(e) {
    const { selectedList } = this.data
    const { index, type } = e.currentTarget.dataset || {}
    let value = e.detail.value
    value = value.replace(/[^\d.]/g, '') // 先把非数字的都替换掉，除了数字和.
    value = value.replace(/^\./g, '') // 必须保证第一个为数字而不是.
    value = value.replace(/\.{2,}/g, '.') // 保证只有出现一个.而没有多个.
    value = value.replace(/^0{2,}/, '0') // 保证只有出现一个0而没有多个0
    value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') // 保证.只出现一次，而不能出现两次以上
    if (value.indexOf('.') < 0 && value.split('').length > 1 && value.split('')[0] == 0) {
      value = value.replace(/^0/g, '') // 整数第一位不能为0
    }
    let priceArr = value.split('.')
    let prcie = ''

    if(type === 'amount'){
      this.setData({
        amount: value
      })
    }else{
      if (value && value < 1) {
        wx.showToast({
          title: '重量区间1~99999',
          icon: 'none',
          duration: 2000,
        })
          this.setData({
            selectedList: selectedList.map((item, i) => ({
              ...item,
              ...(index === i ? { value: 1 } : {})
            }))
          })
        return (prcie = 1)
      }
      if (priceArr.length === 1) {
        if (value > 99999) {
          wx.showToast({
            title: '重量区间1~99999',
            icon: 'none',
            duration: 2000,
          })
          return (prcie = 99999)
        } else {
          prcie = value
        }
      } else if (priceArr.length > 1) {
        let priceEnd = priceArr[1].slice(0, 2)
        prcie = `${priceArr[0]}.${priceEnd}`
        if (prcie > 99999) {
          wx.showToast({
            title: '重量区间1~99999',
            icon: 'none',
            duration: 2000,
          })
          return (prcie = 99999)
        } else {
          prcie = `${priceArr[0]}.${priceEnd}`
        }
      }
      this.setData({
        selectedList: selectedList.map((item, i) => ({
          ...item,
          ...(index === i ? { value: prcie } : {})
        }))
      })
    }
  },
  fieldBlur(e) {
    const { selectedList } = this.data
    const { index, type } = e.currentTarget.dataset || {}
    let value = e.detail.value
    let priceArr = value.split('.')
    let prcie = ''
    if(type === 'amount'){
      if (value.endsWith('.')){
          price = +value
      }
     if (value && value < 0.01) {
      wx.showToast({
        title: '价格区间0.01~9999.99',
        icon: 'none',
        duration: 2000,
      })
        this.setData({
          amount: 0.01
        })
      return (prcie = 0.01)
    }
    if (priceArr.length === 1) {
      if (value > 9999.99) {
        wx.showToast({
          title: '价格区间0.01~9999.99',
          icon: 'none',
          duration: 2000,
        })
        this.setData({
          amount: 9999.99
        })
        return (prcie = 9999.99)
      } else {
        prcie = value
      }
    } else if (priceArr.length > 1) {
      let priceEnd = priceArr[1].slice(0, 2)
      prcie = `${priceArr[0]}.${priceEnd}`
      if (prcie > 9999.99) {
        wx.showToast({
          title: '价格区间0.01~9999.99',
          icon: 'none',
          duration: 2000,
        })
        this.setData({
          amount: 9999.99
        })
        return (prcie = 9999.99)
      } else {
        prcie = `${priceArr[0]}.${priceEnd}`
      }
    }
    this.setData({
      amount: prcie
    })
   }else{
    if (value.endsWith('.')) {
        this.setData({
          selectedList: selectedList.map((item, i) => ({
            ...item,
            ...(index === i ? { value: +value } : {})
          }))
        })
    }
   }


    if (value.endsWith('.')) {
      if (type === 'amount') {
        this.setData({
          amount: +prcie,
        })
      } else {
        this.setData({
          selectedList: selectedList.map((item, i) => ({
            ...item,
            ...(index === i ? { value: +value } : {})
          }))
        })
      }
    }
  },
  /**
   * 下一步
   */
  async goNext() {
    if (this.loading) return
    this.loading = false
    const { selectedList, amount, id } = this.data
    if (selectedList.length <= 0) {
      this.loading = false
      return
    }
    if (selectedList.some(item => !item.value)) {
      wx.showToast({
        title: '您有物品重量没有填写',
        icon: 'none',
        duration: 2000,
      })
      this.loading = false
      return
    }
    if (!amount) {
      wx.showToast({
        title: '回收金额不能为空',
        icon: 'none',
        duration: 2000,
      })
      this.loading = false
      return
    }
    if (!id) {
      wx.showToast({
        title: '该订单没有ID',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    const res = await request.post(api.confirmOrder, {
      id,
      goodsList: selectedList.map(item => ({
        goodsName: item.goodsName,
        goodsId: item.id,
        quantity: +item.value * 1000
      })),
      price: amount
    })
    console.log('确认订单提交接口返回：', res)
    if (res?.httpStatus === 200) {
      wx.showToast({
        title: '修改成功',
        icon: 'none',
        duration: 2000,
      })
      const currentPages = getCurrentPages()
      const secondLastRoute = currentPages[currentPages.length - 2]
      const thirdLastRoute = currentPages[currentPages.length - 3]
      if (secondLastRoute?.route === 'pages/collector-order/collector-order') {
        secondLastRoute?.setData?.({
          activeIndex: 50
        })
        wx.navigateBack({
          delta: 1,
        })
      } else if (thirdLastRoute?.route === 'pages/collector-order/collector-order') {
        thirdLastRoute?.setData?.({
          activeIndex: 50
        })
        wx.navigateBack({
          delta: 2,
        })
      } else {
        jump('collector-order')
      }
    }
    this.loading = false
  },

  // 用户点击右上角分享
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },

})